package com.h117121.fashionshop.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.h117121.fashionshop.core.dom.Product;

public class UpdateProductValidator implements Validator {

	@SuppressWarnings("rawtypes")
	@Override
	public boolean supports(Class clazz) {
		return Product.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {

		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name",
				"required.productname");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "type",
				"required.producttype");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "quantity",
				"required.productquantity");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "amountSold",
				"required.productamountsold");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "price",
				"required.productprice");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "madeIn",
				"required.productmadein");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "views",
				"required.productviews");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "producer",
				"required.productproducer");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "dateAdded",
				"required.productdateadded");

		Product product = (Product) target;
		if (!errors.hasFieldErrors("quantity")) {
			if (product.getQuantity() < 0) {
				errors.rejectValue("quantity", "negative.quantity");
			}
		}
		if (!errors.hasFieldErrors("amountSold")) {
			if (product.getAmountSold() < 0) {
				errors.rejectValue("amountSold", "negative.amountsold");
			}
		}
		if (!errors.hasFieldErrors("price")) {
			if (product.getPrice() < 0) {
				errors.rejectValue("price", "negative.price");
			}
		}
		if (!errors.hasFieldErrors("views")) {
			if (product.getViews() < 0) {
				errors.rejectValue("views", "negative.views");
			}
		}

	}

}
